#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include "Inet_Addr.hpp"

void Usage(const std::string &proc)
{
    std::cout << "Usage: " << proc << "server_ip, server_port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 1.创建socket套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "create socket fail: " << strerror(errno) << std::endl;
        return 1;
    }
    std::cout << "create socket success: " << sockfd << std::endl;

    // 创建客户端同样是需要进行绑定的（ip, port），
    // 但是客户端是很多的，手动绑定容易导致其他客户端不可用, 客户端给服务端发送消息的时候，进行自动绑定

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str()); // 主机序列转网络序列

    while (true)
    {
        std::string inbuffer;
        std::cout << "Please enter# ";
        std::getline(std::cin, inbuffer);

        ssize_t n = sendto(sockfd, inbuffer.c_str(), inbuffer.size(),
                           0, (struct sockaddr *)&server, sizeof(server));
        if (n > 0)
        {
            // 客户端收到消息
            char buffer[1024];
            struct sockaddr_in tmp;
            socklen_t len = sizeof(tmp);
            ssize_t m = recvfrom(sockfd, buffer, sizeof(buffer) - 1,
                                 0, (struct sockaddr *)&tmp, &len);

            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << "server echo# " << buffer << std::endl;
            }
            else
                break;
        }
        else
            break;
    }
    close(sockfd);
    return 0;
}